<?php
namespace app\applet\controller;

use app\applet\model\HouseKeeper;
use app\applet\model\HousingTemplate;
use app\applet\model\IntentionalHouse;
use app\applet\model\OrderHouse;
use app\applet\model\PlatformAccount;
use app\manage\model\AdminUser;
use app\manage\model\ContracTmanagement;
use app\manage\model\TenantManagement;
use think\Controller;
use think\Request;
use app\applet\model\HousingInformation;
use app\applet\model\Shops;
use think\Validate;

class House extends Controller {
    public function __construct(Request $request = null)
    {
//        parent::__construct($request);
    }

    /**
     * 获取房源
     * type     1表示住房，2表示商铺
     * order    1表示智能排序，2表示价格从低到高，3表示价格从高到低
     * house_shape  户型
     *  page
     */
    public function HousingList(){
        $input = input();
        $validate = new Validate([
            ['type', 'require', '不能为空'],
            ['order', 'require', '不能为空'],
            ['page', 'require', '不能为空'],
        ]);
        if(!$validate->check($input))
        {
            returnJson(-1001,  $validate->getError())->send();die;
        }

        $type = intval(input()['type']);
        $order = intval(input()['order']);
        $house_shape = input()['house_shape'];
        $page = input()['page'];
        if ($type == 1) {
            $model=new HousingInformation();
            $data = $model->index($order, $house_shape, $page);
        } elseif ($type == 2) {
            $model=new Shops();
            $data = $model->index($order, $house_shape, $page);
        } else {
            $model=new HousingInformation();
            $data = $model->index($order, $house_shape, $page);
        }

        $model = new AdminUser();
        $data['no_more'] = true;
        foreach ($data['data'] as $k => $item) {
            if ((($page-1) * get_list_rows() + count($data['data'])) >= $data['count']) {
                $data['no_more'] = true;
            } else {
                $data['no_more'] = false;
            }
            $agent = $item['create_id'];
            $detail = $model->detail($agent, 1);
            if ($type == 1) {
                $data['data'][$k]['address'] = $detail['address'] . $detail['street'] .
                    $detail['name'];
                $data['data'][$k]['h_floor_plans'] = $this->dealImage($data['data'][$k]['h_floor_plans']);
                $data['data'][$k]['h_indoor_drawings'] = $this->dealImage($data['data'][$k]['h_indoor_drawings']);
            } elseif ($type == 2) {
                $data['data'][$k]['address'] = $detail['address'] . $detail['street'] .
                    $detail['name'];
                $data['data'][$k]['s_floor_plans'] = $this->dealImage($data['data'][$k]['s_floor_plans']);
                $data['data'][$k]['s_indoor_drawings'] = $this->dealImage($data['data'][$k]['s_indoor_drawings']);
            }
        }
        $data['data'] = array_merge_recursive($data['data']);

        returnJson(200,"成功",$data)->send();die;
    }

    /**
     * 获取房屋详情
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function HouseDetail() {
        $type = input()['type'];
        if ($type == 1) {
            $id = input()['id'];
            $model = new HousingInformation();
            $detail = $model->detail($id);
        } elseif($type == 2) {
            $id = input()['id'];
            $model = new Shops();
            $detail = $model->detail($id);
        }
        $data = [];

        // 两张表的字段不同，组装数据使之返回统一名称
        if ($type == 1) {
            $agent = $detail['create_id'];
            $data['housing_id'] = $id;
            $data['create_id'] = $agent;
            $data['tung_num'] = $detail['h_tung_num'];
            $data['unit_num'] = $detail['h_unit_num'];
            $data['layer_num'] = $detail['h_layer_num'];
            $data['room_number'] = $detail['h_room_number'];
            $data['money'] = $detail['h_money'];
            $data['area'] = $detail['h_area'];
            $data['rooms'] = $detail['h_root'];
            $data['halls'] = $detail['h_guest_room'];
            $data['bathrooms'] = $detail['h_toilet'];
            $data['floor_plans'] = $detail['h_floor_plans'];
            $data['indoor_drawings'] = $detail['h_indoor_drawings'];
            $data['matching'] = $detail['h_matching'];
            $data['info'] = number2chinese($data['rooms']) . "室" . number2chinese($data['halls']) . "厅" . number2chinese($data['bathrooms']) . '卫';
        } elseif ($type == 2) {
            $agent = $detail['create_id'];
            $data['housing_id'] = $id;
            $data['create_id'] = $agent;
            $data['tung_num'] = $detail['s_tung_num'];
            $data['unit_num'] = $detail['s_unit_num'];
            $data['layer_num'] = $detail['s_layer_num'];
            $data['room_number'] = $detail['s_room_number'];
            $data['money'] = $detail['s_money'];
            $data['area'] = $detail['s_area'];
            $data['rooms'] = $detail['s_face_width'];
            $data['halls'] = $detail['s_layer_depth'];
            $data['bathrooms'] = $detail['s_depth'];
            $data['floor_plans'] = $detail['s_floor_plans'];
            $data['indoor_drawings'] = $detail['s_indoor_drawings'];
            $data['matching'] = $detail['s_matching'];
            $data['info'] = "面宽" . $data['rooms'] . "m 层高" . $data['halls'] . "m 进深" . $data['bathrooms'] . 'm';
        }

        $data['floor_plans'] = $this->dealImage($data['floor_plans']);
        $data['indoor_drawings'] = $this->dealImage($data['indoor_drawings']);

        // 获取对应公寓
        $model = new AdminUser();
        $detail = $model->detail($agent, 1);
        $data['apartment_name'] = $detail['name'];
        $data['address'] = $detail['address'] . $detail['street'];

        returnJson(200,"成功",$data)->send();die;

    }

    /**
     * 获取住房模板
     */
    public function HouseShape() {
        $model = new HousingTemplate();
        $data = $model->templateList();
        $info = [];

        foreach ($data as $item) {
            $info[] = ['label' => number2chinese($item['te_root']) . '室' .
                number2chinese($item['te_guest_room']) . '厅' . number2chinese($item['te_toilet']) . '卫',
                    'value' => $item['te_root'] . ',' . $item['te_guest_room'] . ',' . $item['te_toilet']];
        }

        returnJson(200,"成功",$info)->send();die;
    }

    /**
     * 预约看房
     */
    public function OrderHouse() {
        $input = input();

        $validate = new Validate([
            ['token', 'require', '不能为空'],
        ]);
        if(!$validate->check($input))
        {
            returnJson(-2014,  "请先登录")->send();die;
        }

        $validate = new Validate([
            ['keeper_id', 'require', '不能为空'],
            ['page', 'require', '不能为空'],
        ]);
        if(!$validate->check($input))
        {
            returnJson(-1001,  $validate->getError())->send();die;
        }

        $keeper_id = input()['keeper_id'];
        $page = input()['page'];
        $this->is_prohibit($keeper_id);

        $model = new OrderHouse();
        $intentional = $model->OrderList($keeper_id, $page);
        $intentional['no_more'] = true;

        $model_house = new HousingInformation();
        $model_shop = new Shops();
        $model_platform_account = new AdminUser();
        foreach ($intentional['data'] as $k => $item) {
            $intentional['data'][$k]['create_time'] = date("Y-m-d H:i", $intentional['data'][$k]['create_time']);
            if ((($page-1) * get_list_rows() + count($intentional['data'])) >= $intentional['count']) {
                $intentional['no_more'] = true;
            } else {
                $intentional['no_more'] = false;
            }
            if ($item['type'] == 2) {
                $detail = $model_shop->detail($item['house_id']);
//                $intentional['data'][$k]['house_id'] = $detail['shops_id'];
                $intentional['data'][$k]['type'] = 2;
                $intentional['data'][$k]['tung_num'] = $detail['s_tung_num'];
                $intentional['data'][$k]['unit_num'] = $detail['s_unit_num'];
                $intentional['data'][$k]['layer_num'] = $detail['s_layer_num'];
                $intentional['data'][$k]['room_number'] = $detail['s_room_number'];
                $intentional['data'][$k]['money'] = $detail['s_money'];
                $intentional['data'][$k]['area'] = $detail['s_area'];
                $intentional['data'][$k]['rooms'] = $detail['s_face_width'];
                $intentional['data'][$k]['halls'] = $detail['s_layer_depth'];
                $intentional['data'][$k]['bathrooms'] = $detail['s_depth'];
                $intentional['data'][$k]['info'] = '面宽' . $intentional['data'][$k]['rooms'] .'米 层高'. $intentional['data'][$k]['halls'] . '米 进深' . $intentional['data'][$k]['bathrooms'];
                $intentional['data'][$k]['floor_plans'] = $this->dealImage($detail['s_floor_plans']);
                $intentional['data'][$k]['indoor_drawings'] = $this->dealImage($detail['s_indoor_drawings']);
            } else {
                $detail = $model_house->detail($item['house_id']);
//                $intentional['data'][$k]['house_id'] = $detail['housing_id'];
                $intentional['data'][$k]['type'] = 1;
                $intentional['data'][$k]['tung_num'] = $detail['h_tung_num'];
                $intentional['data'][$k]['unit_num'] = $detail['h_unit_num'];
                $intentional['data'][$k]['layer_num'] = $detail['h_layer_num'];
                $intentional['data'][$k]['room_number'] = $detail['h_room_number'];
                $intentional['data'][$k]['money'] = $detail['h_money'];
                $intentional['data'][$k]['area'] = $detail['h_area'];
                $intentional['data'][$k]['rooms'] = $detail['h_root'];
                $intentional['data'][$k]['halls'] = $detail['h_guest_room'];
                $intentional['data'][$k]['bathrooms'] = $detail['h_toilet'];
                $intentional['data'][$k]['info'] = $intentional['data'][$k]['rooms'] .'室'. $intentional['data'][$k]['halls'] . '厅' . $intentional['data'][$k]['bathrooms'] . '卫';
                $intentional['data'][$k]['floor_plans'] = $this->dealImage($detail['h_floor_plans']);
                $intentional['data'][$k]['indoor_drawings'] = $this->dealImage($detail['h_indoor_drawings']);
            }
            $detail = $model_platform_account->detail($detail['create_id'], 1);
            $intentional['data'][$k]['apartment_name'] = $detail['name'];
            $intentional['data'][$k]['address'] = $detail['address'];
            $intentional['data'][$k]['street'] = $detail['street'];
        }

        returnJson(200,"成功",$intentional)->send();
    }

    /**
     * 新增预约看房
     */
    public function AddOrderHouse() {
        $input = input();
        $Ordemodel = new OrderHouse();
        $validate = new Validate([
            ['token', 'require', '不能为空'],
        ]);
        if(!$validate->check($input))
        {
            returnJson(-2014,  "请先登录")->send();die;
        }

        $validate = new Validate([
            ['keeper_id', 'require', '不能为空'],
            ['house_id', 'require', '不能为空'],
            ['type', 'require', '不能为空'],
        ]);
        if(!$validate->check($input))
        {
            returnJson(-1001,  $validate->getError())->send();die;
        }

        $data['keeper_id'] = input()['keeper_id'];
        $data['house_id'] = input()['house_id'];
        $data['type'] = input()['type'];
        $data['order_time'] = input()['order_time'];
//        $data['create_id'] = input()['create_id'];
        $data['status'] = 1;
        $data['admin_status'] = 1;
        $data['create_time'] = time();
        $data['update_time'] = time();
        $this->is_prohibit($data['keeper_id']);

        if (intval($data['type']) == 1) {
            $model = new HousingInformation();
            $detail = $model->detail($data['house_id']);
            $agent = $detail['create_id'];
            $i['keyword1']=$detail['h_tung_num'].'-'.$detail['h_unit_num'].'-'.$detail['h_room_number'];
            $user= $Ordemodel->user($detail['h_agent']);
        } else {
            $model = new Shops();
            $detail = $model->detail($data['house_id']);
            $agent = $detail['create_id'];
            $i['keyword1']=$detail['s_tung_num'].'-'.$detail['s_unit_num'].'-'.$detail['s_room_number'];
            $user= $Ordemodel->user($detail['s_agent']);
        }
        $data['admin_id'] = $agent;
        if ($Ordemodel->uniqueness($data['house_id'], $data['type'], $data['keeper_id'])) {
            returnJson(-2000,"已预约过该房源")->send();die;
        }
        $data = $Ordemodel->m_insert($data);
      //  var_dump($user);exit;
        if($user!=null){
            $keeper= $Ordemodel->keeper_id(input()['keeper_id']);
            $i['first']='有客户提交了预约看房信息，请尽快处理。';
            if($keeper['tenant_name']==null){
                $i['keyword2']=$keeper['name'];
            }else{
                $i['keyword2']=$keeper['tenant_name'];
            }
            $i['openid']=$user;
            $i['keyword3']=$keeper['tel'];
            $i['keyword4']=date('Y年m月d日 H:i:s',time());
            $i['remark']='点击打开消息查看详情进行处理';
            $Ordemodel->Wechat($i);
        }

        returnJson(200,"成功",$data)->send();die;
    }

    /**
     * 移除预约看房
     */
    public function DelOrderHouse() {
        $input = input();

        $validate = new Validate([
            ['token', 'require', 'token不能为空'],
        ]);
        if(!$validate->check($input))
        {
            returnJson(-2014,  "请先登录")->send();die;
        }

        $validate = new Validate([
            ['id', 'require', 'id不能为空'],
            ['user_id', 'require', '用户id不能为空'],
            ['page', 'require', '页码不能为空'],
        ]);
        if(!$validate->check($input))
        {
            returnJson(-1001,  $validate->getError())->send();die;
        }

        $id = input()['id'];
        $page = $input['page'];
        $user_id = $input['user_id'];
        $this->is_prohibit($id);
        $model = new OrderHouse();
        $data['status'] = 2;
        $a = $data;
        $data_tmp = $model->getOne1($user_id, $page);
        if (!empty($data_tmp)) {
            $data = $data_tmp[0];
            $data['create_time'] = date("Y-m-d H:i", $data['create_time']);
            if ($data['type'] == 2) {
                $model_shop = new Shops();
                $detail = $model_shop->detail($data['house_id']);
                $data['type'] = 2;
                $data['tung_num'] = $detail['s_tung_num'];
                $data['unit_num'] = $detail['s_unit_num'];
                $data['layer_num'] = $detail['s_layer_num'];
                $data['room_number'] = $detail['s_room_number'];
                $data['money'] = $detail['s_money'];
                $data['area'] = $detail['s_area'];
                $data['rooms'] = $detail['s_face_width'];
                $data['halls'] = $detail['s_layer_depth'];
                $data['bathrooms'] = $detail['s_depth'];
                $data['info'] = '面宽' . $data['rooms'] .'米 层高'. $data['halls'] . '米 进深' . $data['bathrooms'];
                $data['floor_plans'] = $this->dealImage($detail['s_floor_plans']);
                $data['indoor_drawings'] = $this->dealImage($detail['s_indoor_drawings']);
            } else {
                $model_house = new HouseKeeper();
                $detail = $model_house->detail($data['house_id']);
                $data['type'] = 1;
                $data['tung_num'] = $detail['h_tung_num'];
                $data['unit_num'] = $detail['h_unit_num'];
                $data['layer_num'] = $detail['h_layer_num'];
                $data['room_number'] = $detail['h_room_number'];
                $data['money'] = $detail['h_money'];
                $data['area'] = $detail['h_area'];
                $data['rooms'] = $detail['h_root'];
                $data['halls'] = $detail['h_guest_room'];
                $data['bathrooms'] = $detail['h_toilet'];
                $data['info'] = $data['rooms'] .'室'. $data['halls'] . '厅' . $data['bathrooms'] . '卫';
                $data['floor_plans'] = $this->dealImage($detail['h_floor_plans']);
                $data['indoor_drawings'] = $this->dealImage($detail['h_indoor_drawings']);
            }
            $model_platform_account = new AdminUser();
            $detail = $model_platform_account->detail($detail['create_id'], 1);
            $data['apartment_name'] = $detail['name'];
            $data['address'] = $detail['address'];
            $data['street'] = $detail['street'];
        } else {
            $data = null;
        }

        $model->m_update($id, $a);

        returnJson(200,"成功", $data)->send();die;
    }

    /**
     * 查看租房
     */
    public function rentHouse() {
        $input = input();
        $validate = new Validate([
            ['token', 'require', '不能为空'],
        ]);
        if(!$validate->check($input))
        {
            returnJson(-2014,  "请先登录")->send();die;
        }

        $validate = new Validate([
            ['id', 'require', '不能为空'],
            ['page', 'require', '不能为空'],
        ]);
        if(!$validate->check($input))
        {
            returnJson(-1001,  $validate->getError())->send();die;
        }

        /**
         * 根据看房者id找到电话
         */
        $id = $input['id'];
        $page = $input['page'];
        $this->is_prohibit($id);
        $model = new HouseKeeper();
        $detail = $model->detail($id);
        $tel = $detail['tel'];

        /**
         * 根据电话找到租客id
         */
        $model = new ContracTmanagement();
        $detail = $model->phone2($tel);
        $tenant_ids = [];
        foreach ($detail as $value) {
            array_push($tenant_ids, $value['tenant_id']);
        }

        /**
         * 根据租客id找到合同id
         */
        $detail = [];
        foreach ($tenant_ids as $tenant_id) {
            $model = new ContracTmanagement();
            $detail = array_merge_recursive($model->tenantContractId($tenant_id, $page), $detail);
        }

        $data = [];
        if (!empty($tenant_ids)) {
            if ((($page-1) * get_list_rows() + count($detail['data'])) >= $detail['total']) {
                $detail['no_more'] = true;
            } else {
                $detail['no_more'] = false;
            }
            foreach ($detail['data'] as $k => $contracInfo) {
                /**
                 * 根据合同id找到相关信息
                 */
                $detail1 = $model->T_One($contracInfo['t_c_mid']);
                $data[$k]['id'] = $detail1['c_id'];
                // 房号
                $housing = $detail1['housing'];
                foreach ($housing as $item) {
                    $item['c_number'] = explode('-', $item['c_number']);
                    $data[$k]['house_info'][] = ['room'=>$item['c_number'][0] . '栋' . $item['c_number'][1] . '单元' .$item['c_number'][2], 'type'=>$item['h_type']];
                }

                // 租赁时间
                $data[$k]['start_time'] = $detail1['c_a_time'];
                $data[$k]['end_time'] = $detail1['c_d_time'];

                // 合同编号
                $data[$k]['code'] = $detail1['c_number'];

                // 合同状态
                $data[$k]['status'] = $detail1['c_type'];

                // 图片
                foreach ($detail1['c_img'] as &$item1) {
                    $item1 =  "https://" . $_SERVER['SERVER_NAME'] . $item1;
                }
                $data[$k]['image'] = $detail1['c_img'];

                // 签约时间
                $data[$k]['signing_time'] = $detail1['c_time'];

                // 月租
                $data[$k]['rent'] = $detail1['c_rent_cont'];

                // 押金
                $data[$k]['deposit'] = $detail1['c_deposit_cont'];

                // 支付方式
                $data[$k]['payment_method'] = $detail1['c_payment_method'];
                $data[$k]['c_method'] = $detail1['c_method'];

                // 合租人
                $data[$k]['cotenant'] = count($detail1['tenant']);

                // 入住人
                $data[$k]['residents'] = count($detail1['resident']);
            }
            $detail['data'] = $data;
        } else {
            $detail = [
                'total'=>0,
                'no_more'=>true,
                'data'=>[]
            ];
        }


        returnJson(200,"成功", $detail)->send();die;
    }

    /**
     * 处理图像
     * @param $image
     * @return mixed
     */
    private function dealImage($image) {
        $image = explode(',', $image);
        foreach ($image as &$item) {
            $item =  "https://" . $_SERVER['SERVER_NAME'] . $item;
        }
        return $image;
    }

    /**
     * 判断是否被禁用
     */
    private function is_prohibit($id) {
        $model = new HouseKeeper();
        $detail = $model->detail($id);
        if ($detail['status'] == 3) {
            returnJson(-3001,"用户不存在")->send();die;
        } elseif ($detail['status'] == 2) {
            returnJson(-3000,"用户被禁用")->send();die;
        } else {

        }
    }

}